(function() {
	var startX, startY;
	var clientX, clientY;
	var offsetX = 0, offsetY = 0;
	var scrollJump = 1;
	var scrollRefresh = 5;
	var scrollMiddleZone = 5;
	var scrollCanvas, scrollCtx;
	var extensionUrl = "chrome-extension://ofocddomjlamahlhaiddggjkhbadoidf/";
	var img = new Image();

	document.addEventListener('mousedown', function(ev) {
		if (ev.button != 1) return;
		startX = ev.screenX, startY = ev.screenY;
		clientX = ev.clientX, clientY = ev.clientY;
        offsetX = 0, offsetY = 0;
		scrollTimer = setTimeout(function(){
			if (offsetY > scrollMiddleZone || offsetY < -scrollMiddleZone) window.scrollBy(0,scrollJump);
			scrollTimer = setTimeout(arguments.callee, scrollRefresh);
		}, scrollRefresh);
	}, false);

	document.addEventListener('mousemove', function(ev) {
		if (ev.button != 1) return;
		var currX = ev.screenX, currY = ev.screenY;
		offsetX = currX - startX, offsetY = currY - startY;
		scrollJump = parseInt(offsetY / 6);
		if (scrollTimer) showScrollPicture();
	}, false);
	
	document.addEventListener('mouseup', function(ev) {
		if (ev.button != 1) return;
        if (scrollTimer) {
            clearTimeout(scrollTimer);
            scrollTimer = null;
        }

        if (scrollCtx) {
			scrollCtx.clearRect(0, 0, scrollCanvas.width, scrollCanvas.height);
			scrollCanvas.style.display = 'none';
		}
	}, false);

   function showScrollPicture(){
	   if (offsetY < -scrollMiddleZone) { img.src = extensionUrl+"/img/upScroll.png"; }
	   else if (offsetY > scrollMiddleZone) { img.src = extensionUrl+"img/downScroll.png"; }
	   else { img.src = extensionUrl+"img/middleScroll.png"; }
	   
	   if (!scrollCtx){
		   scrollCanvas = document.createElement('canvas');
		   scrollCanvas.style.cssText = 'z-index:1; position:fixed; top:0; left:0;';
		   scrollCanvas.width = window.innerWidth;
		   scrollCanvas.height = window.innerHeight;
		   document.body.appendChild(scrollCanvas);
		   scrollCtx = scrollCanvas.getContext('2d');
		} else { 
			scrollCanvas.style.display = '';
			scrollCtx.clearRect(0, 0, scrollCanvas.width, scrollCanvas.height);
		}
		scrollCtx.drawImage(img, clientX-14, clientY-14);
	}
})();
